<?php
namespace Admin\Controller;
use Think\Controller;
class AdminController extends CommonController {

    /**
     * 管理员列表
     */
    public function index() {
        $M = M("Admin");

        $keyword = I('get.keyword');
        $role_id = I('get.role_id');


        if(!empty($role_id)) $map['role_id'] = array('in',$role_id);
        if(!empty($keyword)) $map['username'] = array('like','%'.$keyword.'%');

        $count = $M->where($map)->count();
        $Page       = new \Think\Page($count,25);
        $showPage = $Page->show();
        $this->assign("page", $showPage);

        $list = $M->where($map)->order('id')->limit($Page->firstRow.','.$Page->listRows)->select();
        foreach ($list as $key => $val) {

        }
        $this->assign('list',$list);
        $this->display();
    }



    public function add() {
        $Admin = M("Admin");
        if (IS_POST) {
            $id = I('post.id');
            $data = I('post.data');
            $role_id = I('post.role_id');
            $password = I('post.password');
            $username = I('post.username');
            $status = I('post.status');

            $data['status'] = $status;
            $data['role_id'] = $role_id;
            $data['update_time'] = NOW_TIME;

            if($id){
                if(!empty($password)){
                    $data['password'] = md5($password);
                }
                $Admin->where( array('id'=>$id) )->save($data);
                $result = array('status' => 1, 'info' => "操作成功！！", 'url' => U('admin/index'));
            }else{
                $is_exist = $Admin->where( array('username'=>$username) )->count();
                if($is_exist){
                    $this->ajaxReturn(array('status'=>'0','info'=>'该用户名已存在！','url'=>''));
                }
                if(empty($username)){
                    $this->ajaxReturn(array('status'=>'0','info'=>'请输入用户名','url'=>''));
                }
                if(empty($password)){
                    $data['password'] = md5(123456);
                }else{
                    $data['password'] = md5($password);
                }

                $data['username'] = $username;
                $data['create_time'] = NOW_TIME;
                $id = $Admin->add($data);
                $result = array('status' => 1, 'info' => "已经发布", 'url' => U('Product/index'));
            }
            $this->ajaxReturn($result);
        }

        $id = I('get.id',0);
        if($id){
            $info = $Admin->where('id='.$id)->find();
            $this->assign('info',$info);
        }
        $this->display("add");
    }

    public function del(){
        $Admin = M("Admin");
        $ids = I('get.ids');
        $map['id'] = array('in',$ids);

        if ($Admin->where($map)->delete()) {
            $result = array("status"=>1,"info"=>"成功删除",'url'=>'');
        } else {
            $result = array("status"=>0,"info"=>"删除失败，可能是不存在该ID的记录");
        }
        $this->ajaxReturn($result);
    }


}